﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using System.Drawing;
using NPOI.SS.UserModel;
using IHISCETeim.Model;
using System.Reflection;
using System.IO;
using NPOI.SS.Util;


namespace IHISCETeim.Web.Export.AgentSys
{
    public partial class AgentQltyBatchExecl : ExportPageBase
    {
        protected override string xlsTemplateFileName
        {
            get
            {
                return "/Agent/品情故障表.xls";
            }
        }
        protected override string SheetName
        {
            get
            {
                return "品质情报表";
            }
        }
        //protected int QltyId
        //{
        //    get
        //    {
        //        return GetRequestValue<int>("ID", 0);
        //    }
        //}
        /// <summary>
        /// 查找条件
        /// </summary>
        protected string sqlwhere
        {
            get
            {
                return GetRequestValue<string>("q", "");
            }
        }
        protected override string SQLSort
        {
            get
            {
                return " QltyId ASC ";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            InitializeWorkbook();
            //所有需要导出的ID
            int TotalCount = 0;
            DataTable dtids = AgentQltyController.GetPagination(sqlwhere, 1, 999999, SQLSort, ref TotalCount)[0];
            int SheetIndex = 1;
            foreach (DataRow dr in dtids.Rows)
            {
                SingExportProc(Convert.ToInt32(dr["QltyId"]), SheetIndex);
                SheetIndex++;
            }
            hssfworkbook.RemoveSheetAt(0);
            WriteToFile();
        }

        protected void SingExportProc(int QltyId, int SheetIndex)
        {
            AgentQltyInfo objQlty = AgentQltyController.GetByQltyId(QltyId);

            ISheet sheet1 = hssfworkbook.CloneSheet(0);
            hssfworkbook.SetSheetName(SheetIndex, objQlty.ClaimsNumber);

            Type typeUnsu = objQlty.GetType();
            PropertyInfo[] propArry = typeUnsu.GetProperties();

            int rowIndex = 0;
            int cellIndex = 0;
            string trueWriteTag = "";
            object provalue = null;
            string PropertyTypeString = "System.String";
            foreach (var item in propArry)
            {
                provalue = item.GetValue(objQlty, null);//属性值
                PropertyTypeString = item.PropertyType.ToString();
                //获取特性配置值
                object[] objRowIndex = item.GetCustomAttributes(typeof(ExcelRowIndexAttribute), false);
                if (objRowIndex.Length > 0)//说明该属性使用了ExcelRowIndexAttribute标记
                {
                    rowIndex = (objRowIndex[0] as ExcelRowIndexAttribute).RowIndex;

                }
                else
                {
                    continue;//没有行特性,进入下一个
                }
                object[] objCellIndex = item.GetCustomAttributes(typeof(ExcelCellIndexAttribute), false);
                if (objCellIndex.Length > 0)//说明该属性使用了ExcelRowIndexAttribute标记
                {
                    cellIndex = (objCellIndex[0] as ExcelCellIndexAttribute).CellIndex;
                }

                object[] objBoolCell = item.GetCustomAttributes(typeof(ExcelBoolCellAttribute), false);
                if (objBoolCell.Length > 0)//说明该属性使用了ExcelRowIndexAttribute标记
                {
                    trueWriteTag = (objBoolCell[0] as ExcelBoolCellAttribute).TrueWriteTag;
                    if (Convert.ToBoolean(provalue))
                    {
                        provalue = trueWriteTag;
                    }
                    else
                    {
                        provalue = "";
                    }
                    PropertyTypeString = "System.String";
                }


                ConvertDateTypeHelper.WriteExcelDateType(sheet1.GetRow(rowIndex).GetCell(cellIndex), PropertyTypeString, provalue);
                ////写入值
                //if (provalue == null)
                //    provalue = "";
                // sheet1.GetRow(rowIndex).GetCell(cellIndex).SetCellValue(provalue.ToString());

            }
            //2.写入图片
            InsertImages(QltyId,sheet1);
            //3.写入返回入报废相关列表
            InsertDetail(QltyId,sheet1);

            sheet1.ForceFormulaRecalculation = true;
        }
        #region 加载图片方法
        public void InsertImages(int QltyId,ISheet sheet1)
        {
            List<AgentQltyImgInfo> listImg = AgentQltyController.GetAllImgByQltyId_0(QltyId);

            int imgRowIndex = 0;//图片所在起始行号
            int imgCellIndex = 0;//图片所在起始列号
            int imgEndRowIndex = 0;//图片所在结束行号
            int imgEndCellIndex = 0;//图片所在结束列号
            for (int index = 0; index < (listImg.Count > 6 ? 6 : listImg.Count); index++)
            {
                AgentQltyImgInfo objItem = listImg[index];//数据对象
                HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.CreateDrawingPatriarch();
                HSSFClientAnchor anchor;
                //##处理照片位置，【图片左上角为（6, 2）第2+1行6+1列，右下角为（8, 6）第6+1行8+1列】
                //HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0,0, 6, 2, 8, 6);
                switch (index)
                {
                    case 0:
                        imgCellIndex = 6; imgRowIndex = 13; imgEndCellIndex = 8; imgEndRowIndex = 21;
                        sheet1.GetRow(12).GetCell(6).SetCellValue(objItem.Title.ToString());
                        break;
                    case 1:
                        imgCellIndex = 8; imgRowIndex = 13; imgEndCellIndex = 9; imgEndRowIndex = 21;
                        sheet1.GetRow(12).GetCell(8).SetCellValue(objItem.Title.ToString());
                        break;
                    case 2:
                        imgCellIndex = 6; imgRowIndex = 22; imgEndCellIndex = 8; imgEndRowIndex = 30;
                        sheet1.GetRow(21).GetCell(6).SetCellValue(objItem.Title.ToString());
                        break;
                    case 3:
                        imgCellIndex = 8; imgRowIndex = 22; imgEndCellIndex = 9; imgEndRowIndex = 30;
                        sheet1.GetRow(21).GetCell(8).SetCellValue(objItem.Title.ToString());
                        break;
                    case 4:
                        imgCellIndex = 6; imgRowIndex = 31; imgEndCellIndex = 8; imgEndRowIndex = 39;
                        sheet1.GetRow(30).GetCell(6).SetCellValue(objItem.Title.ToString());
                        break;
                    case 5:
                        imgCellIndex = 8; imgRowIndex = 31; imgEndCellIndex = 9; imgEndRowIndex = 39;
                        sheet1.GetRow(30).GetCell(8).SetCellValue(objItem.Title.ToString());
                        break;
                }
                anchor = new HSSFClientAnchor(0, 0, 0, 0, imgCellIndex, imgRowIndex, imgEndCellIndex, imgEndRowIndex);
                anchor.AnchorType = 3;
                try
                {
                    string deskpath = @"E:\Web\IHISCE\";
                    //加载图片，如果出错，则不管
                    HSSFPicture picture = (HSSFPicture)patriarch.CreatePicture(anchor, LoadImage(deskpath + objItem.IMGRelatively.Replace("~", ""), hssfworkbook));
                    picture.LineStyle = LineStyle.DashSys;
                    picture.LineWidth = 12700;
                    picture.SetLineStyleColor(0, 0, 0);
                }
                catch
                {

                }

            }



        }
        public  int LoadImage(string path, HSSFWorkbook wb)
        {
            string newPitPath =FileUploadHelper.GetSmallPic(path, 235, 170);

            //FileStream file = new FileStream(newPitPath, FileMode.Open, FileAccess.Read);
            ////FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
            //byte[] buffer = new byte[file.Length];
            //file.Read(buffer, 0, (int)file.Length);
            //return wb.AddPicture(buffer, PictureType.JPEG);

            using (FileStream file = new FileStream(newPitPath, FileMode.Open, FileAccess.Read))
            {
                byte[] buffer = new byte[file.Length];
                file.Read(buffer, 0, (int)file.Length);
                return wb.AddPicture(buffer, PictureType.JPEG);
            }
        }

        public void InsertDetail(int QltyId, ISheet sheet1)
        {
            List<AgentQltyPartsInfo> listDetail = AgentQltyController.GetAllPartsByQltyId(QltyId);
            int baseFHIndex = 41;
            foreach (AgentQltyPartsInfo item in listDetail)
            {
                //sheet1.GetRow(baseFHIndex).ZeroHeight = false;
                sheet1.GetRow(baseFHIndex).GetCell(1).SetCellValue(item.ItemCode);
                sheet1.GetRow(baseFHIndex).GetCell(3).SetCellValue(item.Dscription);
                sheet1.GetRow(baseFHIndex).GetCell(5).SetCellValue(Convert.ToDouble(item.Quantity));

                baseFHIndex++;
            }

        }

        #endregion

        protected override string GetXlsFileName(string oldFileName)
        {
            //return base.GetXlsFileName(oldFileName);

            return string.Format("{0}{1}.xls", "批量导出品情表", DateTime.Now.ToString("yyyy-MM-dd")).Trim();
        }
    }
}